package com.glela.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.StringUtil;
import com.glela.domain.OpenStoreGoodsReq;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.ShareGoods;
import com.glela.goods.model.request.GoodsRequest;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.model.vo.goods.GoodsPageVo;
import com.glela.goods.model.vo.goods.GoodsRequestVo;
import com.glela.goods.model.vo.goods.GoodsResponse;
import com.glela.goods.model.vo.goods.GoodsSimpleVo;
import com.glela.goods.model.vo.goods.GoodsVo;
import com.glela.goods.model.vo.goods.OpenStoreGoodsVo;
import com.glela.goods.model.vo.goods.StreamerResponse;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.ShareGoodsService;
import com.glela.mq.service.OrderQueueService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.User;
import com.glela.platform.model.request.RequestPageBaseModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

@Controller
@RequestMapping(value = "goods", produces = "application/json;charset=UTF-8")
public class GoodsController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(GoodsController.class);

	@Autowired
	private GoodsService			goodsService;
	@Autowired
	private UserService				userService;
	@Autowired
	private ShareGoodsService		shareGoodsService;
	@Autowired
	private OrderQueueService		orderQueueService;
	@Autowired
	private BaseRestrictionsService	baseRestrictionsService;

	/** 查询开店商品列表 */
	@RequestMapping(value = "/openStoreGoods", method = RequestMethod.POST, consumes = "application/json")
	public @ResponseBody ResponseEntity<?> openStoreGoods(@RequestBody OpenStoreGoodsReq req, HttpServletRequest request) {
		String rslt = null;
		String key = null;
		try {
			if (ParameterUtils.validParams(req.getTalentId())) {
				logger.warn("开店礼包接口请求参数缺失：{}", JsonUtil.toJson(req));
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			req.initHeader(request);
			ResponseUser talentUser = userService.selectUserRoleFormCacheById(req.getTalentId());
			if (talentUser == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
			}
			if (talentUser.isNotStoreLevel()) {
				logger.warn("开店礼包推荐人[{}]不是店主级别，不能推荐[{}]开店", req.getTalentId(), req.getUserId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111, "您的推荐人还没有开店哦，很遗憾不能推荐您开店"), HttpStatus.OK);
			}

			Date nowDay = new Date();
			boolean showAll = false;
			//拦截白名单
			BaseRestrictions OPEN_STORE_GOODS_WHITELIST = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.OPEN_STORE_GOODS_WHITELIST);
			if (OPEN_STORE_GOODS_WHITELIST != null && OPEN_STORE_GOODS_WHITELIST.getExperience() == 1) {
				String[] split = StringUtils.split(OPEN_STORE_GOODS_WHITELIST.getName(), "|");
				if (ArrayUtils.isNotEmpty(split)) {
					showAll = ArrayUtils.contains(split, req.getTalentId().toString());
				}
			}
			key = getTempCacheKey(showAll ? "1" : "0", talentUser.getBindType());
			rslt = queryCacheResult(key);
			if (StringUtils.isEmpty(rslt)) {

				List<OpenStoreGoodsVo> openStoreGoods = goodsService.findOpenStoreGoods(showAll, nowDay);
				List<OpenStoreGoodsVo> rsList = new LinkedList<OpenStoreGoodsVo>();

				if (CollectionUtils.isNotEmpty(openStoreGoods)) {
					//芭米系隐藏特定开店商品
					BaseRestrictions openStoreGoodsConfig = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.OPEN_STORE_GOODS_HIDE_CONFIG);
					if (openStoreGoodsConfig == null || StringUtils.isBlank(openStoreGoodsConfig.getName())) {
						rsList.addAll(openStoreGoods);
					} else {
						String[] hideGoodsIds = StringUtils.split(openStoreGoodsConfig.getName(), "|");
						if (ArrayUtils.isEmpty(hideGoodsIds)) {
							rsList.addAll(openStoreGoods);
						} else {//隐藏
							long[] goodsIds = new long[hideGoodsIds.length];
							for (int i = 0; i < hideGoodsIds.length; i++) {
								goodsIds[i] = NumberUtils.toLong(hideGoodsIds[i], 0);
							}
							for (OpenStoreGoodsVo openStoreGoodsVo : openStoreGoods) {
								if (ArrayUtils.contains(goodsIds, openStoreGoodsVo.getGoodsId())) {
									if (talentUser.getBindType() == 1) {//芭米屏蔽
										continue;
									}
								}
								rsList.add(openStoreGoodsVo);
							}
						}
					}
				}

				//				List<Map<String, Object>> rsltList = new LinkedList<Map<String, Object>>();
				//				Map<String, Object> map99 = new HashMap<String, Object>();
				//				Map<String, Object> map399 = new HashMap<String, Object>();
				//				rsltList.add(map99);
				//				rsltList.add(map399);
				List<OpenStoreGoodsVo> list99 = new LinkedList<OpenStoreGoodsVo>();
				List<OpenStoreGoodsVo> list399 = new LinkedList<OpenStoreGoodsVo>();

				//				map99.put("type", 9900);
				//				map99.put("data", list99);
				//				map399.put("type", 39900);
				//				map399.put("data", list399);

				for (OpenStoreGoodsVo openStoreGoodsVo : rsList) {
					if (openStoreGoodsVo == null) {
						continue;
					}
					if (openStoreGoodsVo.getSalePrice() == 9900) {
						list99.add(openStoreGoodsVo);
					} else if (openStoreGoodsVo.getSalePrice() == 39900) {
						list399.add(openStoreGoodsVo);
					} else {
						logger.warn("开店礼包[{}-{}-{}]不符合分组规则，跳过", openStoreGoodsVo.getGoodsId(), openStoreGoodsVo.getName(), openStoreGoodsVo.getSalePrice());
					}
				}
				rslt = toResultModelJSON(new Object[] { list99, list399 });
			}
			return toRespEntity(toCacheResult(key, rslt));
		} catch (Exception e) {
			getLOGGER().error("查询开店商品列表异常：{}", e.getMessage(), e);
			return new ResponseEntity<>(toErrorModelJSON(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 商品详情(校妆APP) 商品详情
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getGoodsById", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getGoodsById(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getGoodId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			int shareUserRoleId = 0;
			if (request.getShareUserId() > 0) {
				User shareUser = userService.getUser(request.getShareUserId());
				if (shareUser != null) {
					shareUserRoleId = shareUser.getRoleId();
				}
			}
			return goodsService.getGoodsById(request.getGoodId(), shareUserRoleId, request.getRoleId(), StringUtils.isBlank(request.getLivePlanId()) ? "" : request.getLivePlanId());
		} catch (Exception e) {
			logger.error("商品详情异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 商品列表(校妆APP)
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/listGoodsPage", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> listGoodsPage(@RequestBody RequestPageBaseModel request) {
		try {
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(goodsService.selectGoodsPage(request)), HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 返回商品列表根据条件查询(校妆APP) {"pageSize":10,"pageNum":1,"brandId":1}
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/listGoodsPageByBrandId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listGoodsPageByBrandId(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(request.getBrandId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20406), HttpStatus.OK);
			}
			int seeUserRoleId = 0;
			if (request.getUserId() != 0L) {
				User seeUser = userService.getUser(request.getUserId());
				if (seeUser == null) {
					return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C20113), HttpStatus.OK);
				}
				seeUserRoleId = seeUser.getRoleId();
			}
			List<GoodsPageVo> list = goodsService.listGoodsPageByBrandId(request.getBrandId(), seeUserRoleId, request.getStartIndex(), request.getPageSize());
			int count = goodsService.countGoodsPageByBrandId(request.getBrandId());
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<GoodsPageVo>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 新品牌馆商品列表 {"pageSize":10,"pageNum":1,"brandId":1}
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/listGoodsPageByBrandIdNew", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listGoodsPageByBrandIdNew(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(request.getBrandId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20406), HttpStatus.OK);
			}
			return goodsService.listGoodsPageByBrandIdNew(request);
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 根据子分类获取商品列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/listGoodsPageByCategoryId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listGoodsPageByCategoryId(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getCategoryId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (null == request.getUserId()) {
				request.setUserId(0L);
			}
			return goodsService.listGoodsPageByCategoryId(request.getCategoryId(), request.getBrandIdList(), request.getOrder(), request.getUserId(), request.getPageNum(), request.getStartIndex(), request.getPageSize());
		} catch (Exception e) {
			logger.error("商品列表根据条件查询异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 校妆APP根据子分类id查询 所有商品 不重复的 品牌列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/listBrandIdByCategoryId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listBrandIdByCategoryId(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getCategoryId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(goodsService.listBrandIdByCategoryId(request.getCategoryId())), HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 校妆APP首页的热销单品
	 * 
	 * @author 卫耀华
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/goodsHotSales", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> goodsHotSales(@RequestBody GoodsRequest request) {
		try {
			// 如果用户未登录，这里设置个0,做标记是否登录的用途
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			return goodsService.hotSale(request.getUserId().longValue(), request.getPageNum().intValue(), request.getStartIndex(), request.getPageSize().intValue());
		} catch (Exception e) {
			logger.error("热销单品异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 校妆APP商品id集合查询商品图片集合
	 * 
	 * @author 程哲权
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/selectGoodImgByGoodIdList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectGoodImgByGoodIdList(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getGoodIdList())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<GoodsNavigate> GoodsNavigatelist = goodsService.selectGoodImgByGoodIdList(request.getGoodIdList());
			return new ResponseEntity<>(new ResponseResultModel<List<GoodsNavigate>>(GoodsNavigatelist), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询商品图片集合异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 校妆APP讲师推荐商品列表专区
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/jiangShiTuiJianGoods", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> jiangShiTuiJianGoods(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			List<GoodsSimpleVo> list = goodsService.jiangShiTuiJianGoods(request.getUserId(), request.getStartIndex(), request.getPageSize());
			int count = goodsService.countTeacherRecommendGoods();
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<GoodsSimpleVo>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("讲师推荐商品列表异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	 * 后台的横幅/商品列表
	 * 
	 * @author
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/selectGoodsResponse", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectGoodsResponse(@RequestBody GoodsRequest request) {
		try {
			List<GoodsResponse> list = goodsService.selectGoodsResponse(request.getTeacherId());
			return new ResponseEntity<>(new ResponseResultModel<List<GoodsResponse>>(list), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("后台的横幅/商品列表异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	 * 讲师添加横幅和商品
	 * 
	 * @author
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/insertTeacherMessage", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> insertTeacherMessage(@RequestBody GoodsRequestVo GoodsRequestVo) {
		try {
			goodsService.insertTeacherMessage(GoodsRequestVo.getListGoodsResponse(), GoodsRequestVo.getTeacher());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("讲师添加横幅和商品异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	 * 选择横幅
	 * 
	 * @author
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/listStreamerResponse", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listStreamerResponse(@RequestBody GoodsRequest request) {
		try {
			List<StreamerResponse> list = goodsService.listStreamerResponse(request.getTeacherId());
			return new ResponseEntity<>(new ResponseResultModel<List<StreamerResponse>>(list), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("选择横幅异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	 * 选择商品
	 * 
	 * @author
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/GoodsListResponse", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> GoodsListResponse(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getTeacherId(), request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<GoodsListResponse> list = goodsService.GoodsListResponse(request.getTeacherId(), request.getStartIndex(), request.getPageSize(), request.getOrderType());
			int count = goodsService.GoodsListResponseCount();
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<GoodsListResponse>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("选择商品异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	 * 搜索商品
	 * 
	 * @author
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/searchGoodsList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> searchGoodsList(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getLabelName(), request.getTeacherId(), request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<GoodsListResponse> list = goodsService.searchGoodsList(request.getLabelName(), request.getTeacherId(), request.getStartIndex(), request.getPageSize());
			int count = goodsService.searchGoodsListCount(request.getLabelName());
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<GoodsListResponse>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("搜索商品异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	 * 下方最新商品
	 * 
	 * @author
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/listNewGoods", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listNewGoods(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			List<GoodsListResponse> list = goodsService.listNewGoods(request.getUserId(), request.getStartIndex(), request.getPageSize());
			int count = goodsService.listNewGoodsCount();
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<GoodsListResponse>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("下方最新商品", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	 * **********************************************
	 * @Title: getGoodsInfoById
	 * @Description: 根据ID查询Goods
	 * @param @param request
	 * @param @return 设定文件
	 * @return ResponseEntity<?> 返回类型
	 * @throws 异常
	 * @author NingChongQing 作者
	 * @date 2017年7月12日 下午6:05:49 时间 **********************************************
	 */
	@RequestMapping(value = "/getGoodsInfoById", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getGoodsInfoById(@RequestBody GoodsRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getGoodId()) && ParameterUtils.validParams(request.getTalentShareGoodId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			long goodsid = 0l;
			if (!ParameterUtils.validParams(request.getGoodId())) {
				goodsid = request.getGoodId();
			}
			long userId = 0l;// 当前登录人
			if (!ParameterUtils.validParams(request.getUserId())) {
				userId = request.getUserId();
				if (userService.getUserById(request.getUserId()) == null) {//用户不存在
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
				}
			}
			String from = "";
			Integer isFromH5 = 0;// 是否从H5打开分享
			if (!ParameterUtils.validParams(request.getFroms())) {
				from = request.getFroms();
				isFromH5 = 1;
			}
			Long productId = 0l;
			if (!ParameterUtils.validParams(request.getProductId())) {
				productId = request.getProductId();
			}
			int limitTimeSaleId = 0;
			if (!ParameterUtils.validParams(request.getLimitTimeSaleId())) {
				limitTimeSaleId = request.getLimitTimeSaleId();
			}
			long shareGoodsId = 0l;
			if (!ParameterUtils.validParams(request.getTalentShareGoodId())) {
				shareGoodsId = request.getTalentShareGoodId();
			}
			// 校妆姐姐ID
			Integer xzJJUserId = Integer.valueOf(BaseConstants.XZ_SISTER + "");
			// 店主用户ID  默认校妆姐姐店铺的店主ID
			Integer storeUserId = xzJJUserId;
			if (!ParameterUtils.validParams(request.getUserId())) {
				User user = this.userService.getUserById(request.getUserId());
				User storeUser = this.userService.getUserByPersionId(user.getRecommendFrom());
				storeUserId = storeUser.getId().intValue();
			}
			// 角色  默认为校妆姐姐
			String role = "MAJOR";
			if (storeUserId.intValue() != xzJJUserId.intValue()) {
				role = "GENERAL";
			}
			tempKey = "temp:goodsinfo:" + role + "-" + goodsid + "-" + productId + "-" + limitTimeSaleId + "-" + isFromH5;
			rslt = getRedisUtil().get(tempKey);

			if (StringUtils.isEmpty(rslt)) {
				if (goodsid == 0) {
					ShareGoods sharGoods = this.shareGoodsService.selectShareGoodsById(shareGoodsId);
					if (sharGoods == null) {
						rslt = toErrorModelJSON(ErrorEnum.C40007);
						return toRespEntity(rslt);
					}
					goodsid = sharGoods.getGoodId();
				}
				GoodsVo goodsVo = goodsService.getGoodsInfoById(goodsid, productId, limitTimeSaleId, userId, storeUserId, from);
				if (goodsVo == null) {
					rslt = toErrorModelJSON(ErrorEnum.C40007);
				} else {
					getRedisUtil().setex(tempKey, 86400, JSONObject.toJSONString(goodsVo));
					// 缓存商品详情页有效时间
					getRedisUtil().setex(tempKey + "-effectivetime", 30, tempKey);
					goodsVo.setLivePlanId(request.getLivePlanId());
					rslt = toResultModelJSON(goodsVo);
					// 缓存商品详情页对象(有效期1天)
				}
			} else {
				String keyEffectiveTime = getRedisUtil().get(tempKey + "-effectivetime");
				if (StringUtil.isEmpty(keyEffectiveTime)) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("redisKey", tempKey);
					params.put("goodsid", goodsid);
					params.put("productId", productId);
					params.put("limitTimeSaleId", limitTimeSaleId);
					params.put("userId", userId);
					params.put("storeUserId", storeUserId);
					params.put("from", from);
					// 加一条队列信息 重新缓存商品详情信息
					this.orderQueueService.updateGoodsInfoRedisCache(params);
				}
				GoodsVo _vo = JSONObject.parseObject(rslt, GoodsVo.class);
				_vo.setLivePlanId(request.getLivePlanId());
				//				logger.error(" result json : {}" , JSONObject.toJSONString(_vo));
				return toRespEntity(toResultModelJSON(_vo));
			}
		} catch (Exception e) {
			getLOGGER().error("查询商品详情异常:{}", e.getMessage(), e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}

		return toRespEntity(rslt);
	}

	/**
	 * 
	 * **********************************************
	 * @Title: selectMaterialsByGoodsIdWithPage
	 * @Description: 查询商品所有的素材信息（分页）
	 * @param @param request
	 * @param @return
	 * @return ResponseEntity<?>
	 * @throws @author NingChongQing
	 * @date 2017年11月27日 下午3:18:12 **********************************************
	 */
	@RequestMapping(value = "/selectMaterialsByGoodsIdWithPage", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectMaterialsByGoodsIdWithPage(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getGoodId(), request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<Map<String, Object>> materialsList = this.goodsService.selectMaterialsByGoodsIdWithPage(request.getGoodId(), request.getStartIndex(), request.getPageSize());
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<Map<String, Object>>(materialsList.size(), request.getPageSize(), request.getPageNum(), materialsList)), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("查询商品详情异常:{}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * **********************************************
	 * @Title: goodsInfoPreview
	 * @Description: 商品详情页预览接口
	 * @param @param request
	 * @param @return
	 * @return ResponseEntity<?>
	 * @throws @author NingChongQing
	 * @date 2017年12月12日 下午4:19:11 **********************************************
	 */
	@RequestMapping(value = "/goodsInfoPreview", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> goodsInfoPreview(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getGoodId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 校妆姐姐ID
			Integer xzJJUserId = Integer.valueOf(BaseConstants.XZ_SISTER + "");
			GoodsVo goodsVo = goodsService.goodsInfoPreview(request.getGoodId(), xzJJUserId);
			return new ResponseEntity<>(new ResponseResultModel<>(goodsVo), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("商品详情预览异常:{}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}
